package com.liy.teaching.common;

import com.baomidou.mybatisplus.extension.service.IService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;


/**
 * 基础Controller, 实现基本的CRUD
 *
 * @param <BizService> 业务Service
 * @param <T> 返回的 模型对象
 */
public class BaseController<BizService extends IService<T>,  T extends Serializable> {

    @Autowired
    private BizService bizService;

    public BaseController() {
    }

    /**
     * 新增单条记录
     * @param entity
     * @return
     */
    @RequestMapping(value = { "/add" }, method = { RequestMethod.POST })
    @ResponseBody
    public ResultVo add(@RequestBody T entity) {
        try {
            bizService.save(entity);
            return ResultVo.ok(entity,"新增成功");
        }
        catch (Exception e) {
            return ResultVo.failed(entity,"新增失败: " + e.getMessage());
        }
    }

    /**
     * 根据 主键ID 删除
     * @param id
     * @return
     */
    @RequestMapping(value = { "/del/{id}"}, method = { RequestMethod.DELETE, RequestMethod.GET })
    @ResponseBody
    public ResultVo removeById(@PathVariable("id")  String id) {
        try {
            bizService.removeById(id);
            return ResultVo.ok("根据主键ID删除成功");
        }
        catch (Exception e) {
            return ResultVo.failed("根据主键ID删除失败: " + e.getMessage());
        }
    }

    /**
     * 根据 ID 选择更新
     *
     * @param entity 实体对象
     */
    @RequestMapping(value = { "/update" }, method = { RequestMethod.PUT, RequestMethod.POST })
    @ResponseBody
    public ResultVo update(@RequestBody final T entity) {
        try {
            bizService.updateById(entity);
            return ResultVo.ok(entity,"根据ID更新成功");
        }
        catch (Exception e) {
            return ResultVo.failed("根据ID更新失败: " + e.getMessage());
        }
    }

    /**
     * 单条查询 根据主键ID 单条查询
     * @param id
     */
    @RequestMapping(value = {"/get/{id}"},  method = {RequestMethod.GET})
    @ResponseBody
    public ResultVo get(@PathVariable("id") String id) {
        try {
            T byId = bizService.getById(id);

            if(byId !=null){
                return ResultVo.ok(byId);
            }
            return ResultVo.ok(null,"没有这条记录");
        } catch (Exception e) {
            System.err.println(e.getStackTrace());
            return ResultVo.failed("单条查询失败: " + e.getMessage());
        }
    }

}

